/**************************************************************************************************************
 * @copyright Copyright (c) 2015—2024 Uniorange Internet Design Co., LTD. All rights reserved.
 * @author Uniorange Internet Design Co., LTD.
 *
 * This file is part of the App project. Copyright © Uniorange Internet Design Co., Ltd. All Rights Reserved.
 * Unauthorized copying of this file, via any medium is strictly prohibited Proprietary and confidential.
 *
 **************************************************************************************************************/
package com.jinyu.gateway.registry;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 邱金波
 * @version V0.1
 * @className SubscribeCenter
 * @description 订阅中心，保存的是订阅者相关信息
 * @date 2024/09/20 14:24
 */
@Data
@Slf4j
public class SubscribeCenter {
    private static final ConcurrentHashMap<String, Set<String>> subscribeMap = new ConcurrentHashMap<>();

    public static void subscribe(String name, List<String> subscribeList) {
        synchronized (SubscribeCenter.class) {
            Set<String> subscribeSet = subscribeMap.get(name);
            if (subscribeSet == null) {
                subscribeSet = new HashSet<>();
                subscribeMap.put(name, subscribeSet);
            }
            subscribeSet.addAll(subscribeList);
        }
    }

    /**
     * 解除订阅关系
     *
     * @param name
     * @param subscribeList
     */
    public static void unSubscribe(String name, List<String> subscribeList) {
        synchronized (SubscribeCenter.class) {
            Set<String> subscribeSet = subscribeMap.get(name);
            if (subscribeSet != null) {
                subscribeSet.removeAll(subscribeList);
            }
        }
    }

    /**
     * 根据服务名称获取订阅列表
     *
     * @param name
     * @return
     */
    public static Set<ServerNode> getNotifyList(String name) {
        synchronized (SubscribeCenter.class) {
            HashSet<ServerNode> serverNodeSet = new HashSet<>();
            subscribeMap.forEach((k, v) -> {
                if (v.contains(name)) {
                    serverNodeSet.addAll(RegistryCenter.getServerNodeByName(name));
                }
            });
            return serverNodeSet;
        }
    }

    public static List<String> unSubscribeByName(String name) {
        synchronized (SubscribeCenter.class) {
            List<String> strings = new ArrayList<>();
            subscribeMap.forEach((k, v) -> {
                if (v.contains(name)) {
                    strings.add(k);
                }
            });
            Set<String> subscribeSet = subscribeMap.get(name);
            if (subscribeSet != null) {
                subscribeSet.removeAll(strings);
            }
            return strings;
        }
    }
}
